<template>
  <view>
    <u-navbar title="分润设置"></u-navbar>
    <frecharts v-if="b_zf != 0" :list="StatFrecharts"></frecharts>
    <u-form :model="form" ref="uForm" label-width="220rpx">
      <!-- 独立分润 -->
      <u-form-item :label="zflabel">
        <view class="switchbox">
          <u-switch
            :disabled="lookfalg"
            v-model="b_zf"
            activeValue="3"
            @change="b_zfchange()"
          ></u-switch>
        </view>
      </u-form-item>
      <template v-if="Station.b_zf == 1 || Station.b_zf == 2">
        <u-form-item label="流量费收款支付宝">
          <view class="switchbox">
            {{ StationOldMsg.zfb }}
          </view>
        </u-form-item>
        <u-form-item label="流量费收款姓名">
          <view class="switchbox">
            {{ StationOldMsg.zfbxm }}
          </view>
        </u-form-item>
      </template>

      <formselect
        v-if="b_zf != 0 && !station0falg"
        v-model="mode"
        :disabled="lookfalg"
      ></formselect>

      <!-- StationOldMsg -->
    </u-form>

    <view
      v-if="b_zf != 0 && mode == 1"
      style="padding: 20rpx 20rpx; color: #2093f5"
    >
      此模式只支持有阶梯电量计费的汽车桩！！！
    </view>
    <view class="" v-if="b_zf != 0">
      <statfritem
        v-for="(item, key) in StatFr"
        :key="key"
        :item="item"
        :usearchs="USearchs"
        :mode="mode"
        :statfrper="statfrper"
        :station="Station"
        @itemchange="itemchange"
        :statfr="StatFr"
        :station0falg="station0falg"
        :i="key"
        :disabled="lookfalg"
      ></statfritem>
    </view>
    <formz ref="formz" v-if="!lookfalg" :inputs="inputs"></formz>
    <pfridpage
      ref="pfridpage"
      :station="Station"
      :user="user"
      :usearchs="USearchs"
      :mode="mode"
      :statfr="StatFr"
      @itemchange="itemchange"
    ></pfridpage>
    <zmodal ref="zmodal"></zmodal>
    <fixedbtn v-if="!lookfalg">
      <view class="u-flex" style="flex: 1">
        <u-button
          v-if="!station0falg"
          :custom-style="btnstyle"
          type="primary"
          :loading="loading"
          @click="pfridadd()"
        >
          添加分润方
        </u-button>
        <u-button
          :loading="loading"
          :custom-style="btnstyle"
          type="primary"
          @click="updata()"
        >
          保存修改
        </u-button>
      </view>
    </fixedbtn>
  </view>
</template>

<script>
  import frecharts from "./components/frecharts.vue";
  import formselect from "./components/formselect.vue";
  import statfritem from "./components/StatFritem.vue";
  import pfridpage from "./components/pfridpage.vue";
  import qs from "qs";
  export default {
    name: "StatFrecharts",
    components: {
      pfridpage,
      frecharts,
      formselect,
      statfritem,
    },
    data() {
      return {
        inputs: [
          {
            label: "验证码",
            value: "yzm",
            type: "yzm",
          },
        ],
        loading: false,
        user: {},
        form: {},
        query: {},
        b_zf: "0",
        Station: {},
        StatFrold: [],
        StatFr: [],
        mode: "0",
        USearchs: [],
        StationOldMsg: {},
        btnstyle: {
          flex: "1",
          padding: "8rpx 20rpx",
          fontSize: "32rpx",
          margin: "0 20rpx",
        },
        b_zfchangefalg: false,
        typepfrids: {
          0: "代理商",
          2: "物业",
          5: "自定义",
          8: "一级分润方",
          9: "二级分润方",
        },
      };
    },
    onLoad(query) {
      if (!query.id) {
        let locationquery = window.location.search;
        locationquery = locationquery.replace("?", "");
        query = qs.parse(locationquery);
      }
      this.query = query;
      this.init();
    },
    computed: {
      zflabel() {
        if (this.b_zfchangefalg) {
          return "独立分润";
        }
        if (this.Station.b_zf == "1") {
          return "每日支付";
        }
        if (this.Station.b_zf == "2") {
          return "按月支付";
        }
        // if (this.b_zf == 3) {
        // 	return "独立分润"
        // }
        return "独立分润";
      },
      lookfalg() {
        return this.user.utype == "7";
      },
      StatFrecharts() {
        return this.StatFr.filter((e) => {
          return e.del != "1";
        });
      },
      station0falg() {
        return this.Station.id == this.user.pcs;
      },
      statfrper() {
        let r = "per";
        if (this.StatFr.length != 0) {
          if (this.StatFr[0].pernx && this.StatFr[0].pernx != 0) {
            r = "pernx";
          }
        }
        return r;
      },
    },
    watch: {
      mode(n, o) {
        this.modechange();
      },
    },
    methods: {
      b_zfchange() {
        this.b_zfchangefalg = true;
      },
      sybfbyz() {
        if (this.mode == 0) {
          let r = this.sybfb(this.StatFr);
          if (r != 0) {
            this.$u.toast(`当前区域分润还有${r}%没有设置，无法保存！！`);
          }
          return r;
        }
        let mode1 = this.sybfb(
          this.StatFr.filter((e) => {
            return e.mode == "1";
          })
        );

        if (mode1 != 0) {
          this.$u.toast(`当前区域电费分润还有${mode1}%没有设置，无法保存！！`);
          return mode1;
        }

        let mode2 = this.sybfb(
          this.StatFr.filter((e) => {
            return e.mode == "2";
          })
        );
        if (mode2 != 0) {
          this.$u.toast(
            `当前区域服务费分润还有${mode2}%没有设置，无法保存！！`
          );
          return mode2;
        }
        let mode3 = this.sybfb(
          this.StatFr.filter((e) => {
            return e.mode == "3";
          })
        );
        if (mode3 != 0) {
          this.$u.toast(`当前区域卡分润还有${mode3}%没有设置，无法保存！！`);
          return mode3;
        }
        return 0;
      },
      fridtype(frid) {
        let user = this.USearchs.find((e) => {
          return e.frid == frid;
        });
        if (user) {
          let types = [
            {
              label: "代理商",
              value: "0",
              uUsertype: ["0", "14", "18", "19"],
            },
            {
              label: "平台",
              value: "1",
              uUsertype: ["999"],
            },
            {
              label: "物业",
              value: "2",
              uUsertype: ["11", "20"],
            },
            {
              label: "自定义",
              value: "5",
              uUsertype: ["12"],
            },
          ];
          types = types.find((e) => {
            return e.uUsertype.find((f) => {
              return f == user.utype;
            });
          });
          return types ? types.value : 0;
        }
        return 0;
      },
      async updata() {
        await this.$refs.formz.validate();
        this.loading = true;

        let reqs = [];
        let array = this.$u.deepClone(this.StatFr);
        if (this.b_zf != this.Station.b_zf) {
          reqs.push({
            url: "/Stationedt",
            data: {
              ...this.Station,
              b_zf: this.b_zf,
            },
          });
        }
        if (this.b_zf != "0") {
          let regex = /^(100|\d{1,2})$/;
          for (let index = 0; index < array.length; index++) {
            if (this.b_zf == "0") {
              break;
            }
            let element = array[index];
            if (element.type == "10") {
              element.type = this.fridtype(element.frid);
            }
            if (this.mode == "0") {
              element.mode = "0";
            } else {
              if (element.mode == "0") {
                element.mode = "1";
              } else if (element.mode == "2_2") {
                element.mode = "2";
                element.type = "10";
              }
            }

            if (
              element.del != 1 &&
              element.type != 10 &&
              !regex.test(element.per)
            ) {
              this.$u.toast(`分润比例必须是0-100的整数`);
              this.loading = false;
              return;
            }
            let has = this.StatFrold.find((f) => {
              return f.frid == element.frid;
            });
            if (element.del == 1) {
              if (element.frid.indexOf("new") < 0) {
                reqs.push({
                  url: "/StatFrdel",
                  data: {
                    frid: element.frid,
                    // pfrid: element.pfrid,
                    // pcs: element.pcs,
                  },
                });
              }
            } else if (element.frid.indexOf("new") >= 0) {
              reqs.push({
                url: "/StatFradd",
                data: element,
              });
            } else {
              if (
                has &&
                element.type == has.type &&
                element.mc == has.mc &&
                element.per == has.per &&
                element.mode == has.mode
              ) {
                reqs.push({
                  url: "",
                  data: element,
                });
              } else {
                reqs.push({
                  url: "/StatFredt",
                  data: element,
                  olddata: has,
                });
              }
            }
          }

          let frdata = array
            .filter((e) => {
              return e.del != "1" && e.type != 10;
            })
            .map((e) => {
              return {
                frid: !e.pfrid || e.pfrid == 0 ? e.frid : e.pfrid,
                mode: e.mode,
              };
            });
          let erre = frdata.find((e) => {
            let r = frdata.filter((f) => {
              return f.frid == e.frid && f.mode == e.mode;
            });
            return r.length != "1";
          });
          if (erre) {
            let str = `分润方${this.StatFrtypefn(
              erre
            )}分润案中存在重复的分润方案，无法保存！！`;
            this.$refs.zmodal.init({
              content: str,
            });
            this.loading = false;
            return;
          }

          let sybfb = this.sybfbyz();

          if (sybfb != 0) {
            this.loading = false;
            return;
          }

          reqs = reqs.filter((e) => {
            return e.url != "";
          });
          reqs = reqs.sort((a, b) => {
            if (a.url == b.url) {
              if (b.url == "/StatFredt") {
                let aedtper =
                  parseFloat(a.olddata.per) - parseFloat(a.data.per);
                let bedtper =
                  parseFloat(b.olddata.per) - parseFloat(b.data.per);
                return bedtper - aedtper;
              }
              return 0;
            }
            if (a.url == "/StatFrdel") {
              return -1;
            } else if (a.url == "/StatFradd") {
              return 1;
            } else {
              return 1;
            }
          });
        }
        try {
          for (let index = 0; index < reqs.length; index++) {
            const e = reqs[index];
            e.data.per = parseFloat(e.data.per);
            if (e.url == "/StatFrdel") {
              delete e.data.per;
            }

            let requests = async () => {
              await this.$z.request(e.url, e.data);
              await this.StatFraddedtfn(e.url, e.data);
              await new Promise((resolve) => {
                setTimeout(() => {
                  resolve();
                }, 1000);
              });
            };
            await requests();
          }
        } catch (err) {
          let str = "操作失败";
          if (err[0].par == "err_sql") {
            str = "该分润内还有余额，需要提现后才能删除!!";
          }

          this.$u.toast(str);
          this.loading = false;
          return;
        }

        if (reqs.length == 0) {
          this.$u.toast("请修改后保存");
          this.loading = false;
          return;
        }
        this.loading = false;
        this.$refs.zmodal.init({
          content: "修改成功",
          confirm: () => {
            this.$z.back();
          },
        });
      },
      StatFrtypefn(p) {
        if (p.pfrid == 0 || !p.pfrid) {
          let dquUser = this.USearchs.find(function (e) {
            return e.frid == p.frid;
          });
          if (dquUser) {
            let mc = dquUser.uUser;
            if (dquUser.uxm) {
              mc += "_" + dquUser.uxm;
            }
            return mc;
          }
          return "新" + this.typepfrids[p.type];
        }

        let dquUser = this.usearchs.find(function (e) {
          return e.frid == p.pfrid;
        });
        if (dquUser) {
          let mc = dquUser.uUser;
          if (dquUser.uxm) {
            mc += "_" + dquUser.uxm;
          }
          return mc;
        } else {
          return "";
        }
      },
      async StatFraddedtfn(url, data) {
        if (!data.pfrid || isNaN(data.pfrid)) {
          return;
        }
        let user = this.USearchs.find((e) => {
          return e.frid == data.pfrid;
        });
        if (!user || [18, 19, 20].indexOf(Number(user.utype)) < 0) {
          return;
        }
        if (url == "/StatFradd") {
          let array = [this.Station];
          let UToPcs = await this.$z.request("/UToPcs", {
            uUser: user.uUser,
          });
          for (let index = 0; index < array.length; index++) {
            const element = array[index];

            let dqUToPcs = UToPcs.find(function (e) {
              return e.pcs == element.id;
            });
            if (!dqUToPcs) {
              await this.$z.request("/UToPcsadd", {
                uUser: user.uUser,
                pcs: element.id,
              });
            }
          }
        }
        if (url == "/StatFrdel") {
          let array = [this.Station];
          let UToPcs = await this.$z.request("/UToPcs", {
            uUser: user.uUser,
          });
          for (let index = 0; index < array.length; index++) {
            const element = array[index];
            let dqUToPcs = UToPcs.find(function (e) {
              return e.pcs == element.id;
            });
            if (dqUToPcs) {
              await this.$z.request("/UToPcsdel", {
                uUser: user.uUser,
                id: dqUToPcs.id,
              });
            }
          }
        }
      },
      pfridadd() {
        this.$refs.pfridpage.init();
      },
      modechange() {
        if (this.mode == "1") {
          this.$refs.zmodal.init({
            content: `此模式只支持有阶梯电量计费的汽车桩！！！`,
          });
        }
        this.StatFr.forEach((e) => {
          if (this.mode == "0") {
            e.mode = "0";
          } else if (e.mode == "0") {
            e.mode = "1";
          }
        });
      },
      itemchange(data) {
        this.StatFr = data;
      },
      sybfb(data = this.StatFr) {
        let r = 100;
        data.forEach((e) => {
          if (e.del != 1) {
            if (isNaN(parseFloat(e.per))) {
              e.per = 0;
            }
            r = Number(r).subtr(Number(e.per));
          }
        });
        return r;
      },
      async init() {
        if (!this.query.id) {
          this.$u.toast("无id");
          return;
        }
        uni.showLoading({
          title: "加载中",
        });
        let Station = await this.$z.request("/Station", {
          id: this.query.id,
        });
        // Station[0].b_zf = "2"
        this.Station = Station[0];
        let user = await this.$store.dispatch("user/getuser");
        console.log(user, "user");
        this.user = user;
        await this.$store.dispatch("upw/getUpw");
        // this.$refs.formz.init();
        this.USearchs = await this.$z.request("/USearchAllfrid", {
          b_pt: 1,
        });
        this.USearchs = this.USearchs.filter(function (e) {
          let xsutypes =
            ["8", "14", "16"].indexOf(user["utype"].toString()) >= 0
              ? ["14", "16", "2", "9", "17", "19", "20"]
              : [
                  "0",
                  "1",
                  "7",
                  "10",
                  "11",
                  "2",
                  "9",
                  "14",
                  "15",
                  "18",
                  "19",
                  "20",
                  "21",
                ];
          if (xsutypes.indexOf(e.utype) >= 0) {
            return true;
          } else {
            return false;
          }
        });
        this.b_zf = this.Station.b_zf == "0" ? "0" : "3";
        let StatFr = await this.$z.request("/StatFr", {
          pcs: this.query.id,
        });

        this.StatFrold = this.$u.deepClone(StatFr);
        StatFr = StatFr.map((e) => {
          if (e.type == "10") {
            e.mode = "2_2";
          }
          return e;
        });
        let Station0falg = this.query.id == this.user.pcs;
        if (Station0falg) {
          StatFr = StatFr.filter((e) => {
            return e.type == 8 || e.type == 9;
          });
          ["8", "9"].forEach((type) => {
            let typefr = StatFr.find(function (e) {
              return e.type == type;
            });
            if (!typefr) {
              let adddata = {
                frid: "new" + StatFr.length,
                per: this.sybfb(StatFr),
                pcs: this.query.id,
                pcsxs: this.query.idxs,
                pfrid: "0",
                pernx: "0",
                nxl: "0",
                mode: "0",
              };
              adddata.type = type;
              adddata.mc = this.Station.pcs + "-" + this.typepfrids[type];
              StatFr.push(adddata);
            }
          });
        }
        if (this.Station.b_dyfr != 1) {
          StatFr.forEach(function (e) {
            if (e.type == "9") {
              e.del = "1";
              e.per = 0;
            } else if (e.type == "8" && e.per != 100) {
              e.per = 100;
            }
          });
        }

        this.StatFr = this.$u.deepClone(StatFr);
        this.mode = StatFr.find((e) => {
          return e.mode && e.mode != "0";
        })
          ? "1"
          : "0";

        if (this.Station.b_zf == 1 || this.Station.b_zf == 2) {
          let StationOldMsg = await this.$z.request("/StationOldMsg", {
            id: this.query.id,
          });
          this.StationOldMsg =
            StationOldMsg.length == 1 ? StationOldMsg[0] : {};
        }
        uni.hideLoading();
        // StationOldMsg
        // StatFr
      },
    },
  };
</script>

<style lang="scss">
  .switchbox {
    display: flex;
    flex: 1;
    justify-content: flex-end;
    align-items: center;
  }
</style>
